<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { listByUserSelect } from '@/utils/format'
import type { PickerConfirmEventParams } from 'vant'
import type { UserI } from '@/types/user'
import { updateUser, getUserInfo } from '@/AGC/utils/user'
import { useUserStore } from '@/stores/user'

const store = useUserStore()
const userInfo = ref<UserI>({ ...store.userInfo })

const rules = {
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [{ required: true, message: '请选择年龄', trigger: 'blur' }],
  height: [{ required: true, message: '请选择身高', trigger: 'blur' }],
  weight: [{ required: true, message: '请选择体重', trigger: 'blur' }],
}
const formRef = ref<FormInstance>()
const onSubmit = async () => {
  await formRef.value?.validate()
  // 向云数据库更新用户信息
  try {
    await updateUser(userInfo.value)
    // 重新获取用户信息
    const result = await getUserInfo(store.token)
    // 提示
    if (result) {
      store.setUserInfo(result)
      ElMessage.success('资料更新成功')
    }
  } catch (error) {
    ElMessage.error('资料更新失败')
    Promise.reject(error)
  }
}
// Picker 显示数据
const columns = ref<{ text: string; value: string }[]>([])
const weightColumns = ref<{ text: string; value: string }[][]>([])
// Picker 显示类型
const showPopupType = ref<string>('')

watch(showPopupType, (value) => {
  if (value) {
    if (listByUserSelect(value) != undefined) {
      if (value == 'weight') {
        weightColumns.value = listByUserSelect(value)! as { text: string; value: string }[][]
      } else {
        columns.value = listByUserSelect(value)! as { text: string; value: string }[]
      }
    }
  }
})
// Picker 确认事件
const onConfirm = ({ selectedValues }: PickerConfirmEventParams) => {
  switch (showPopupType.value) {
    case 'age':
      userInfo.value.age = selectedValues[0].toString()
      break
    case 'height':
      userInfo.value.height = selectedValues[0].toString()
      break
    case 'weight':
      userInfo.value.weight = selectedValues[0] + '.' + selectedValues[1] + 'kg'
      break
  }
  showPopupType.value = ''
}
// 是否可以复原
const isRestore = computed(() => {
  return (
    userInfo.value.nickname != store.userInfo.nickname ||
    userInfo.value.phone != store.userInfo.phone ||
    userInfo.value.email != store.userInfo.email ||
    userInfo.value.sex != store.userInfo.sex ||
    userInfo.value.age != store.userInfo.age ||
    userInfo.value.height != store.userInfo.height ||
    userInfo.value.weight != store.userInfo.weight
  )
})
// 复原用户信息
const onRestore = () => {
  userInfo.value = { ...store.userInfo }
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">更新资料</div>
    </template>
    <div class="update-body">
      <el-form label-width="80px" :model="userInfo" :rules="rules" ref="formRef">
        <el-form-item label="昵称" prop="nickname">
          <el-input placeholder="请输入昵称" v-model="userInfo.nickname" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input placeholder="请输入手机号码" v-model="userInfo.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="userInfo.email" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userInfo.sex" name="sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age" class="MyRadio">
          <div>
            <van-field
              v-model="userInfo.age"
              is-link
              readonly
              placeholder="请选择年龄"
              @click="showPopupType = 'age'"
            />
            <van-popup :show="showPopupType == 'age'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="身高" prop="height" class="MyRadio">
          <div>
            <van-field
              v-model="userInfo.height"
              is-link
              readonly
              placeholder="请选择身高"
              @click="showPopupType = 'height'"
            />
            <van-popup :show="showPopupType == 'height'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="体重" prop="weight" class="MyRadio">
          <div>
            <van-field
              v-model="userInfo.weight"
              is-link
              readonly
              placeholder="请选择体重"
              @click="showPopupType = 'weight'"
            />
            <van-popup :show="showPopupType == 'weight'" round position="center">
              <van-picker
                :columns="weightColumns"
                @cancel="showPopupType = ''"
                @confirm="onConfirm"
              />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label-width="20px">
          <div style="display: flex; justify-content: space-between; width: 100%; margin-top: 15px">
            <el-button type="info" @click="onRestore" style="width: 35%" :disabled="!isRestore"
              >复原</el-button
            >
            <el-button type="primary" @click="onSubmit" style="width: 35%">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  width: 30%;
  background-color: rgb(247, 248, 250);

  .update-body {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 30px;

    .el-form {
      width: 80%;

      .MyRadio {
        ::v-deep(.el-form-item__label) {
          padding: 6px 12px 0 0;
        }
      }

      .van-popup {
        width: 30%;
      }
    }
  }
}
</style>
